package at.chrenko.tu.vs.shared;

import java.io.IOException;

import org.bouncycastle.util.encoders.Base64;

public class Base64Decorator extends ChannelDecorator {

	public Base64Decorator(Channel channel) {
		super(channel);
	}
	
	@Override
	public void send(byte[] message) throws IOException {
		if(message == null)
			return;
		
		byte[] base64Message = Base64.encode(message);
		decoratedChannel.send(base64Message);
		
//		String msg = new String(message, "UTF-8");
//		
//		if(msg.startsWith(Command.LOGIN + " ")) {
//			msg = msg.replaceFirst(Command.LOGIN + " ", "");
//			byte[] base64Message = Base64.encode(msg.getBytes("UTF-8"));
//			msg = Command.LOGIN + " " + new String(base64Message, "UTF-8");
//			decoratedChannel.send(msg);
//		}
//		else if(msg.startsWith(Command.OK + " ")) {
//			msg = msg.replaceFirst(Command.OK + " ", "");
//			byte[] base64Message = Base64.encode(msg.getBytes("UTF-8"));
//			msg = Command.OK + " " + new String(base64Message, "UTF-8");
//			decoratedChannel.send(msg);
//		}
//		else {
//			byte[] base64Message = Base64.encode(message);
//			decoratedChannel.send(base64Message);
//		}
	}
	
	@Override
	public byte[] receive() throws IOException {
		byte[] data = decoratedChannel.receive();
		
		if(data == null)
			return null;
		
		data = Base64.decode(data);
		return data;
		
//		String msg = new String(data, "UTF-8");
//		
//		if(msg.startsWith(Command.LOGIN + " ")) {
//			msg = msg.replaceFirst(Command.LOGIN + " ", "");
//			byte[] message = Base64.decode(msg.getBytes("UTF-8"));
//			msg = Command.LOGIN + " " + new String(message, "UTF-8");
//			return msg.getBytes("UTF-8");
//		}
//		else if(msg.startsWith(Command.OK + " ")) {
//			msg = msg.replaceFirst(Command.OK + " ", "");
//			byte[] message = Base64.decode(msg.getBytes("UTF-8"));
//			msg = Command.OK + " " + new String(message, "UTF-8");
//			return msg.getBytes("UTF-8");
//		}
//		else {
//			byte[] message = Base64.decode(msg.getBytes("UTF-8"));
//			return message;
//		}
	}
}
